package org.theonept.travian.model;

import java.io.Serializable;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.theonept.travian.util.HttpUtil;

import android.text.format.DateUtils;

public class Message implements Serializable {

	/**
     *
     */
	private static final long serialVersionUID = -4887649342673371106L;

	private String expediteur;
	private Long id;
	private String sujet;
	private Boolean read;
	private String message;
	private String submitText;
	private String tValue;

	private Date date;

	private Compte compte;

	/**
	 * @return the expediteur
	 */
	public String getExpediteur() {
		return expediteur;
	}

	/**
	 * @param expediteur
	 *            the expediteur to set
	 */
	public void setExpediteur(String expediteur) {
		this.expediteur = expediteur;
	}

	/**
	 * @return the id
	 */
	public Long getId() {
		return id;
	}

	/**
	 * @param id
	 *            the id to set
	 */
	public void setId(Long id) {
		this.id = id;
	}

	/**
	 * @return the sujet
	 */
	public String getSujet() {
		return sujet;
	}

	/**
	 * @param sujet
	 *            the sujet to set
	 */
	public void setSujet(String sujet) {
		this.sujet = sujet;
	}

	/**
	 * @return the message
	 */
	public String getMessage() {
		return message;
	}

	/**
	 * @param message
	 *            the message to set
	 */
	public void setMessage(String message) {
		this.message = message;
	}

	public static List<Message> getMessages(Compte compte) {
		List<Message> messages = new ArrayList<Message>();
		SimpleDateFormat sm = new SimpleDateFormat("dd.MM.yy hh:mm");
		SimpleDateFormat sm2 = new SimpleDateFormat("dd.MM.yy");
		Document document = HttpUtil.getDocumentFromUrl(compte.getUrlServeur() + "nachrichten.php");
		Integer nbpage = 1;
		Elements lastPage = document.getElementsByAttributeValue("class", "last");
		if (!lastPage.isEmpty()) {
			String nbPageTemp = lastPage.first().attr("href").split("page=")[1];
			nbpage = Integer.valueOf(nbPageTemp);
		}

		for (int i = 1; i <= nbpage; i++) {
			Document documentPage = HttpUtil.getDocumentFromUrl(compte.getUrlServeur()
					+ "nachrichten.php?t=0&o=0&page=" + i);
			Element content = documentPage.getElementById("overview");
			List<Element> listMessage = content.children().last().children();
			for (Element element : listMessage) {

				if (!element.getElementsByAttributeValueStarting("href", "nachrichten.php?id").isEmpty()) {
					Message message = new Message();

					message.setSujet(element.getElementsByAttributeValueStarting("href", "nachrichten.php?id").first()
							.text().trim());
					message.setId(Long.valueOf(element
							.getElementsByAttributeValueStarting("href", "nachrichten.php?id").first().attr("href")
							.replace("nachrichten.php?id=", "").replace("&t=0", "")));
					String dateText = element.getElementsByAttributeValue("class", "dat").first().text();
					try {

						message.setDate(sm.parse(dateText));
					} catch (ParseException e) {
						String heure = dateText.split(" ")[1];
						Date time = new Date(System.currentTimeMillis() - DateUtils.DAY_IN_MILLIS);

						try {
							message.setDate(sm.parse(sm2.format(time) + " " + heure));
						} catch (ParseException e1) {
							// TODO Auto-generated catch block
							e1.printStackTrace();
						}

					}
					message.setExpediteur(element.getElementsByAttributeValueStarting("href", "spieler.php?uid=")
							.first().text().trim());
					message.setRead(!element.getElementsByAttributeValueStarting("class", "messageStatus").first()
							.attr("class").contains("messageStatusUnread"));
					message.setCompte(compte);
					messages.add(message);
				}
			}
		}
		return messages;
	}

	public void getContent() {

		Document documentMessage = HttpUtil
				.getDocumentFromUrl(compte.getUrlServeur() + "nachrichten.php?id=" + getId());
		Element messageElement = documentMessage.getElementById("content");
		setMessage(messageElement.getElementById("message").html());
		Element elementRepondre = messageElement.getElementById("answer");
		setSubmitText(elementRepondre.getElementsByAttributeValue("type", "submit").first().attr("value"));
		settValue(elementRepondre.getElementById("t").attr("value"));
		setRead(true);

	}

	/**
	 * @return the compte
	 */
	public Compte getCompte() {
		return compte;
	}

	/**
	 * @param compte
	 *            the compte to set
	 */
	public void setCompte(Compte compte) {
		this.compte = compte;
	}

	public static void newMessage(Compte compte, String destinataire, String sujet, String message) {
		Document documentSendMessage = HttpUtil.getDocumentFromUrl(compte.getUrlServeur() + "nachrichten.php?t=1");
		String c = documentSendMessage.getElementById("send").getElementsByAttributeValue("name", "c").first()
				.attr("value");
		List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
		nameValuePairs.add(new BasicNameValuePair("an", destinataire));
		nameValuePairs.add(new BasicNameValuePair("be", sujet));
		nameValuePairs.add(new BasicNameValuePair("message", message));
		nameValuePairs.add(new BasicNameValuePair("c", c));

		String result = HttpUtil.excutePost(compte.getUrlServeur() + "nachrichten.php", nameValuePairs);
	}

	public void reply(String newMessage) {

		List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
		nameValuePairs.add(new BasicNameValuePair("id", getId().toString()));
		nameValuePairs.add(new BasicNameValuePair("t", gettValue()));
		nameValuePairs.add(new BasicNameValuePair("s1", getSubmitText()));

		String resultForm = HttpUtil.excutePost(compte.getUrlServeur() + "nachrichten.php", nameValuePairs);
		Document documentReply = Jsoup.parse(resultForm);
		String cValue = documentReply.getElementById("send").getElementsByAttributeValue("name", "c").first()
				.attr("value");
		String destinataire = documentReply.getElementById("receiver").attr("value");
		String subject = documentReply.getElementById("subject").getElementsByAttributeValue("type", "text").first()
				.attr("value");
		String oldMessage = documentReply.getElementById("message").val();
		nameValuePairs.clear();
		nameValuePairs.add(new BasicNameValuePair("an", destinataire));
		nameValuePairs.add(new BasicNameValuePair("be", subject));
		nameValuePairs.add(new BasicNameValuePair("message", newMessage + "\n" + oldMessage));
		nameValuePairs.add(new BasicNameValuePair("c", cValue));
		nameValuePairs.add(new BasicNameValuePair("p", id.toString()));

		String result = HttpUtil.excutePost(compte.getUrlServeur() + "nachrichten.php", nameValuePairs);

	}

	/**
	 * @return the submitText
	 */
	public String getSubmitText() {
		return submitText;
	}

	/**
	 * @param submitText
	 *            the submitText to set
	 */
	public void setSubmitText(String submitText) {
		this.submitText = submitText;
	}

	/**
	 * @return the tValue
	 */
	public String gettValue() {
		return tValue;
	}

	/**
	 * @param tValue
	 *            the tValue to set
	 */
	public void settValue(String tValue) {
		this.tValue = tValue;
	}

	/**
	 * @return the date
	 */
	public Date getDate() {
		return date;
	}

	/**
	 * @param date
	 *            the date to set
	 */
	public void setDate(Date date) {
		this.date = date;
	}

	/**
	 * @return the read
	 */
	public Boolean getRead() {
		return read;
	}

	/**
	 * @param read
	 *            the read to set
	 */
	public void setRead(Boolean read) {
		this.read = read;
	}
}
